<?php
  include("./include/config.inc.php");
  if(!isset($_SESSION['s_activId']))
  {
    header('location:checkLogin.php');
  }
  
  $today = date('Y-m-d');
  $todate = date('Y-m-d');
  $displayArray = array();
  $countInstallment = 0;
  $msg = "";
  $m= 0;
  if(!isset($_SESSION['s_activId']))
  {
    $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
  	header("Location:checkLogin.php");
  }
  if(isset($_REQUEST['dateSubmit']))
  {
  	$todate = $_POST['toDateYear']."-".$_POST['toDateMonth']."-".$_POST['toDateDay'];
  	$today = $todate;
    $selectAll = "SELECT loanId
                    FROM loan
                   WHERE isDeleted = 'N'";
    $selectAllRes = mysql_query($selectAll);
    while($selectAllRow = mysql_fetch_array($selectAllRes))
    {
      $chkInterestTodayAll = "SELECT loanId, pendingAmount, monthlyInterestRs, loanDate
                                FROM loan 
                               WHERE loan.loanDate < '".$todate."'
                                 AND loanId = ".$selectAllRow['loanId'];
      $chkInterestTodayAllRes = mysql_query($chkInterestTodayAll);
      $chkInterestTodayAllRow = mysql_fetch_array($chkInterestTodayAllRes);
      $chkInterestTodayAllRows = mysql_num_rows($chkInterestTodayAllRes);
      if($chkInterestTodayAllRows > 0)
      {
        for($i = $chkInterestTodayAllRow['loanDate'];$i <= $todate;$i=date('Y-m-d',strtotime('+30 day',strtotime($i))))
	      {
          $chkLoneavailableRecord = "SELECT `loanId` 
                                       FROM `interestreceived`
                                      WHERE `dateOfInstallment` = '".$i."'
                                        AND `loanId` = ".$selectAllRow['loanId'];
          $chkLoneavailableRecordRes = mysql_query($chkLoneavailableRecord);
          $chkLoneavailableRecordNumRows = mysql_num_rows($chkLoneavailableRecordRes);
          if($chkLoneavailableRecordNumRows == 0)
          {
            $insertInterestRecived = "INSERT INTO `interestreceived` (`loanId`, `pendingAmount`, `interest`, `dateOfInstallment`, `receivedDate`, `isReceive`)
                                           VALUES ('".$chkInterestTodayAllRow['loanId']."','".$chkInterestTodayAllRow['pendingAmount']."',
                                                   '".$chkInterestTodayAllRow['monthlyInterestRs']."','".$i."','0000-00-00',0)";
            $insertInterestRecivedRes = mysql_query($insertInterestRecived);
          }
        }
      }
    }
  }
  
  if(isset($_REQUEST['installmentReceived']))
  {
  	foreach ($_REQUEST['installmentReceived'] as $key => $value)
  	{
  		if($value > 0)
  		{
  			"<BR/> ".$key." : ".$value;
  			for($i=1;$i<=$value;$i++)
  			{
  				$findLoanIdQuery = "SELECT loanId
  				                      FROM interestreceived
  				                     WHERE interestReceivedId = ".$key;
          $findLoanIdQueryResult = mysql_query($findLoanIdQuery);
          $findLoanIdQueryResultRow = mysql_fetch_array($findLoanIdQueryResult);
  				$findInstallmenQuery = "SELECT MIN(interestReceivedId) AS interestReceivedId
  				                          FROM interestreceived
  				                         WHERE loanId = ".$findLoanIdQueryResultRow['loanId']."
  				                           AND isReceive = '0'";
          $findInstallmenResult = mysql_query($findInstallmenQuery);
          if($findInstallmenRow = mysql_fetch_array($findInstallmenResult))
          {
          	
  				  $updateQuery = "UPDATE interestreceived
  				                     SET isReceive = '1', receivedDate = '".$today."'
  				                   WHERE interestReceivedId = ".$findInstallmenRow['interestReceivedId'];
            $updateResult = mysql_query($updateQuery);
            if(!$updateResult)
            {
              die("Installmant received : ".$countInstallment."<br/> Please Select Specific Date");
            }
            
            //insert into rojmel
            $selectForRojmel = "SELECT loanId,interest,receivedDate
                                  FROM interestreceived
                                 WHERE interestReceivedId = ".$findInstallmenRow['interestReceivedId'];
            $selectForRojmelRes = mysql_query($selectForRojmel);
            $selectForRojmelRow = mysql_fetch_array($selectForRojmelRes);
            $loanId = $selectForRojmelRow['loanId'];
	          $amount = $selectForRojmelRow['interest'];
	          $date   = $selectForRojmelRow['receivedDate'];
            $insertRojmel = "INSERT INTO rojmel(`date`,`amount`,`debitCredit`,`accountId`,`loanId`)
                                   VALUES ('".$date."',".$amount.",'Cr',2,".$loanId.")";
            $insertRojmelRes = mysql_query($insertRojmel);
            $countInstallment = $countInstallment + 1 ;
          }
  			}
  		}
  	}
  }
  $selectForDisplay = "SELECT interestreceived.interestReceivedId, interestreceived.loanId, COUNT(isReceive) AS pendingInstallment, party.partyName, party.mobile, ((loan.pendingAmount*loan.monthlyInterestRs)/loan.loanAmount) AS interest, SUM((loan.pendingAmount*loan.monthlyInterestRs)/loan.loanAmount) AS inRs, interestreceived.dateOfInstallment, interestreceived.receivedDate 
                         FROM interestreceived
                         JOIN loan ON interestreceived.loanId = loan.loanId
                         JOIN party ON loan.partyId = party.partyId 
                        WHERE isReceive = 0
                          AND loan.isSold != 'Y'
                          AND loan.isDeleted != 'Y'
                          AND dateOfInstallment <= '".$todate."'
                     GROUP BY loanId";
  $selectForDisplayRes = mysql_query($selectForDisplay);
  while($selectForDisplayRow = mysql_fetch_array($selectForDisplayRes))
  {
    $displayArray[$m]['interestReceivedId'] = $selectForDisplayRow['interestReceivedId'] ;
    $displayArray[$m]['loanId']             = $selectForDisplayRow['loanId'] ;
    $displayArray[$m]['pendingInstallment'] = $selectForDisplayRow['pendingInstallment'] ;
    $displayArray[$m]['partyName']          = $selectForDisplayRow['partyName'] ;
    $displayArray[$m]['mobile']             = $selectForDisplayRow['mobile'] ;
    $displayArray[$m]['inRs']               = $selectForDisplayRow['inRs'] ;
    $displayArray[$m]['receivedDate']       = $selectForDisplayRow['receivedDate'] ;
    $displayArray[$m]['interest']           = $selectForDisplayRow['interest'] ;
    $displayArray[$m]['dateOfInstallment']  = $selectForDisplayRow['dateOfInstallment'] ;
    $m++;
  }
  //select party for party combo
  $arrParty = array();
  $i=0;
  $selParty="SELECT `partyId`,`partyName` 
               FROM `party`";
  $selPartyRes=mysql_query($selParty);
  while($selPartyResRow=mysql_fetch_array($selPartyRes))
  {
    $arrParty['partyName'][$i] = $selPartyResRow['partyName'];
    $arrParty['partyId'][$i]   = $selPartyResRow['partyId'];
    $i++;
  } 
  include("./bottom.php");
  $smarty->assign('today',$today);  
  $smarty->assign('msg',$msg);  
  $smarty->assign('displayArray',$displayArray);  
  $smarty->assign('arrParty',$arrParty);  
  $smarty->display('loanDetail.tpl');
?>